<?php
/**
 * Order.php
 * Author: luoji (867404364@qq.com)
 * Date: 2020-12-20
 * Time: 11:25
 */

namespace App\Tables;


class Order extends Base
{
    const Make_Status_No = 2;
    const Make_Status_Ing = 3;
    const Make_Status_Ok = 1;
    const Make_Status_Arr = [1,2,3];

    const Make_Status_Cn = [1 => '已完成', 2 => '未制作', 3 => '制作中'];

    const Delivery_Status_No = 2;
    const Delivery_Status_Ing = 3;
    const Delivery_Status_Ok = 1;
    const Delivery_Status_Arr = [1,2,3];
    const Delivery_Status_Cn = [1 => '已完成', 2 => '未送货', 3 => '送货中'];

    const Pay_status_No = 2;
    const Pay_status_Ok = 1;

    const Dumped = 1;
    const No_Dumped = 0;

    const Deliver_Method_Ok = 1;
    const Deliver_Method_Cn = [1 => '自取', 2 => '送货上门', 3 => '发快递', 4 => '发物流', 5=>'其它'];

    public function details()
    {
        return $this->hasMany(OrderDetail::class,  'oid', 'id')->orderBy('id', 'desc');
    }

    public function pays()
    {
        return $this->hasMany(OrderPay::class, 'oid', 'id')->orderBy('id', 'desc');
    }

    public function events()
    {
        return $this->hasMany(OrderEvent::class, 'oid', 'id')->orderBy('id', 'desc');
    }

    public static function getDebt($cid)
    {
        return (double) self::where('customer_id', $cid)
            ->where('pay_status', self::Pay_status_No)
            ->where('dumped', self::No_Dumped)
            ->select(\DB::raw('SUM(real_price-paid_price) as debt'))->value('debt');
    }

    public static function getDebtTime($cid)
    {
        $addTime = (int) self::where('customer_id', $cid)
            ->where('pay_status', self::Pay_status_No)
            ->orderBy('id', 'asc')->value('add_time');
        if(empty($addTime)) { return 0;}
        return ceil((time()-$addTime) / 86400);
    }
}